package com.wolfcode.goods.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.wolfcode.common.core.domain.TreeSelect;
import com.wolfcode.common.utils.StringUtils;
import com.wolfcode.goods.domain.info.SelectCategoryInfo;
import com.wolfcode.goods.domain.vo.GoodsCategoryVo;
import com.wolfcode.goods.service.IGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wolfcode.goods.mapper.GoodsCategoryMapper;
import com.wolfcode.goods.domain.GoodsCategory;
import com.wolfcode.goods.service.IGoodsCategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * 物品分类信息Service业务层处理
 * 
 * @author wolfcode
 * @date 2022-12-10
 */
@Service
public class GoodsCategoryServiceImpl implements IGoodsCategoryService 
{
    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private IGoodsService goodsService;

    /**
     * 查询物品分类信息
     * 
     * @param id 物品分类信息主键
     * @return 物品分类信息
     */
    @Override
    public GoodsCategory selectGoodsCategoryById(Long id)
    {
        return goodsCategoryMapper.selectGoodsCategoryById(id);
    }

    /**
     * 查询物品分类信息列表
     * 
     * @param goodsCategory 物品分类信息
     * @return 物品分类信息
     */
    @Override
    public List<GoodsCategory> selectGoodsCategoryList(GoodsCategory goodsCategory)
    {
        return goodsCategoryMapper.selectGoodsCategoryList(goodsCategory);
    }

    /**
     * 构建前端所需要下拉树结构
     * @param categories 商品分类列表
     * @return 下拉树结构
     */
    @Override
    public List<TreeSelect> buildTreeSelect(List<GoodsCategory> categories) {
        List<GoodsCategory> categorieTrees = buildTree(categories);
        return categorieTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param categories 商品分类列表
     * @return 树结构列表
     */

    public List<GoodsCategory> buildTree(List<GoodsCategory> categories)
    {
        List<GoodsCategory> returnList = new ArrayList<GoodsCategory>();
        List<Long> tempList = new ArrayList<Long>();
        for (GoodsCategory category : categories)
        {
            tempList.add(category.getId());
        }
        for (GoodsCategory category : categories)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getParentId()))
            {
                recursionFn(categories, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = categories;
        }
        return returnList;
    }
    /**
     * 新增物品分类信息
     * 
     * @param categoryVo 物品分类信息
     * @return 结果
     */
    @Override
    public void insertGoodsCategory(GoodsCategoryVo categoryVo)
    {
        Long parentId = categoryVo.getParentId();
        GoodsCategory category = new GoodsCategory();
        BeanUtils.copyProperties(categoryVo,category);
        String parentBusiPath = null;
        if(parentId != null) {
            GoodsCategory parentCategory = goodsCategoryMapper.selectGoodsCategoryById(parentId);
            parentBusiPath = parentCategory.getBusiPath();
        }
        goodsCategoryMapper.insertGoodsCategory(category);
        if(parentBusiPath!=null) {
            category.setBusiPath(parentBusiPath + ',' + category.getId());
        } else {
            category.setBusiPath(category.getId().toString());
        }
        goodsCategoryMapper.updateGoodsCategory(category);
    }

    /**
     * 修改物品分类信息
     * 
     * @param categoryVo 物品分类信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGoodsCategory(GoodsCategoryVo categoryVo)
    {
        Long parentId = categoryVo.getParentId();
        Long id = categoryVo.getId();
        GoodsCategory goodsCategory = new GoodsCategory();
        BeanUtils.copyProperties(categoryVo,goodsCategory);
        String busiPath = "";
        if(parentId != null) {
            Assert.state(id.equals(parentId),"分类不能放到自己下");
            GoodsCategory parentCategory = goodsCategoryMapper.selectGoodsCategoryById(parentId);
            busiPath = parentCategory.getBusiPath() + ',' + id;
            goodsCategory.setParentId(parentId);
        } else {
            busiPath = categoryVo.getId().toString();
        }
        goodsCategory.setBusiPath(busiPath);
        goodsCategoryMapper.updateGoodsCategory(goodsCategory);
        List<GoodsCategory> categories = goodsCategoryMapper.selectGoodsCategoryListById(categoryVo.getId());
        for (GoodsCategory category : categories) {
            if(category.getId().equals(id)) continue;
            category.setBusiPath(busiPath + ',' + category.getId());
            goodsCategoryMapper.updateGoodsCategory(category);
        }
    }


    /**
     * 删除物品分类信息信息
     * 
     * @param id 物品分类信息主键
     * @return 结果
     */
    @Override
    public void deleteGoodsCategoryById(Long id)
    {
        Assert.notNull(id,"非法参数");
        List<GoodsCategory> goodsCategories = goodsCategoryMapper.selectGoodsCategoryListById(id);
        // 查询是否有库存，进行判断是否删除
        Long[] ids = goodsCategories.stream().map(GoodsCategory::getId).toArray(Long[]::new);
        int count = goodsService.selectGoodsCountByCategoryIds(ids);
        Assert.state(count==0,"该物品仍然存在库存,不能删除");
        goodsCategoryMapper.deleteGoodsCategoryByIds(ids);
    }



    /**
     * 递归列表
     */
    private void recursionFn(List<GoodsCategory> list, GoodsCategory t)
    {
        // 得到子节点列表
        List<GoodsCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (GoodsCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<GoodsCategory> getChildList(List<GoodsCategory> list, GoodsCategory t)
    {
        List<GoodsCategory> tlist = new ArrayList<GoodsCategory>();
        Iterator<GoodsCategory> it = list.iterator();
        while (it.hasNext())
        {
            GoodsCategory n = (GoodsCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<GoodsCategory> list, GoodsCategory t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public List<SelectCategoryInfo> selectGoodsCategory() {
        return goodsCategoryMapper.selectGoodsCategory();
    }
}
